<?php

/**
 *  @author  Lynn Cho <lynncho@live.com>
 *  @createTime  2016-9-19 9:42:02
 *  @copyright  shewen technology
 *  @descrition  detail with group tree, etc
 */
class ServiceGroupModel extends CI_Model {

    private $groupList = array();

    public function __construct() {
        parent::__construct();
        self::getDBGroupList();
    }

    private function getDBGroupList() {
        $this->groupList = $this->db
                ->get('service_group')
                ->result_array();
    }

    /**
     * generate tree with format array
     * @param array $items array([0] => array('id' => 1, 'parentid' => 0))
     * @return array
     */
    public function getGroupTree() {
        foreach ($this->groupList as $key => $item) {
            $item['text'] = $item['name'];
            $formatItems[$item['id']] = $item;
        }
        $tree = array();
        foreach ($formatItems as $key => $item) {
            if (isset($formatItems[$item['parentid']])) {
                $formatItems[$item['parentid']]['children'][] = &$formatItems[$item['id']];
            } else {
                $tree[] = &$formatItems[$item['id']];
            }
        }
        return $tree;
    }

    /**
     * real group, have service
     * @return array
     */
    public function getRealGroup() {
        return self::getChildren($this->groupList);
    }

    private function getChildren($groupList) {
        foreach ($groupList as $key => $item1) {
            foreach ($groupList as $item2) {
                if ($item1['id'] == $item2['parentid']) {
                    unset($groupList[$key]);
                }
            }
        }
        return $groupList;
    }

    public function getGroupList() {
        return $this->groupList;
    }

    public function getLevel($groupid) {
        foreach ($this->groupList as $val) {
            if ($groupid == $val['id']) {
                if ($val['parentid'] == 0) {
                    return $val['id'];
                } else {
                    return self::getLevel($val['parentid']) . '.' . $val['id'];
                }
            }
        }
    }

}
